<?php

namespace app\db\controller;

use think\Cache;
use think\Config;
use think\Db;
use think\Validate;

/**
 * 模板相关接口
 * @author MSQ 2021-8-5
 * MSG提示:DB02000-DB02014
 */
class DbTemplate extends Common
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['getQuoteTemplateList','getTemplateSecondItem','getInfoBySecondItemId','getTemplateDirectoryList','getTemplateQuestionList'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
        //设置过滤方法
        $this->request->filter(['trim']);
    }

    /**
     * 获取可引用模板列表
     * @author MSQ 2021-8-5
     */
    public function getQuoteTemplateList()
    {
        $usercare_id = $this->auth->getUsercareinfo('id');

        $parent_id = $_POST['parent_id'];// 父级数据库id，0为总库
        $list = model('DbTemplate')->getQuoteTemplateList($parent_id,$usercare_id);
        
        $this->success('获取成功',$list);
    }
    /**
     * 获取目录列表
     * @author MSQ 2021-8-9
     */
    public function getTemplateDirectoryList()
    {
        $template_id = $_POST['template_id'];
        $is_hide     = isset($_POST['is_hide']) ? $_POST['is_hide'] : 0;// 是否需要隐藏目录 1需要0不需要
        if (!$template_id) $this->error('DB02001:参数错误');

        $list = model('DbTemplateRelationItem')->getTemplateDirectoryList($template_id,$is_hide);

        $this->success('获取成功',$list);
    }
    /**
     * 获取变量列表
     * @author MSQ 2021-8-9
     */
    public function getTemplateQuestionList()
    {
        $database_id = $_POST['database_id'];
        $template_id = $_POST['template_id'];
        $item_id     = $_POST['item_id']; // 目录ID
        $need        = $_POST['need']; // need_question need_option need_hide need_data
        if (!$template_id || !$item_id) $this->error('DB02002:参数错误');

        $itemInfo = model('DbTemplateRelationItem')->getDetails($item_id,$template_id);
        if (!$itemInfo || $itemInfo['type'] != 1) $this->error('DB02003:目录信息错误');
        # 优先读取缓存里的变量列表
        $cacheKey = model('DbTemplateRelationQuestion')->getQuestionListCacheKey($template_id,$item_id,$need);
        $list = Cache::get($cacheKey);

        if ($list === false) {
            $list = model('DbTemplateRelationItem')->getTemplateItemQuestionList($template_id,$item_id,$need);
        }
        $this->success('获取成功',$list);
    }
    /**
     * 模块设置
     * 新增/修改-目录/模块
     * @author MSQ 2021-8-10
     */
    public function setItem()
    {
        $database_id    = $_POST['database_id'];
        $template_id    = $_POST['template_id'];
        $item_id        = $_POST['item_id']; // 目录/模块ID 有则编辑，无则新增
        $parent_id      = $_POST['parent_id']; // 上级目录/模块id
        $item_name      = $_POST['item_name']; // 目录/模块名称
        $type           = $_POST['type']; // 类型 1目录2模块
        $usercare_id    = $this->auth->getUsercareinfo('id');

        if (!$item_name || !$template_id || !$type || !$database_id) $this->error('DB02004:参数错误');

        $check = model('DbTemplateRelationItem')->checkSetItem($database_id,$template_id,$parent_id,$item_name,$item_id,$type);
        if ($check['code'] != 1) $this->error('DB02005:'.$check['msg']);

        Db::startTrans();
        $res = model('DbTemplateRelationItem')->setItem($template_id,$parent_id,$item_name,$item_id,$type,$usercare_id);
        if (!$res) {
            Db::rollback();
            $this->error('DB02006:操作失败');
        }
        Db::commit();

        $this->success('操作成功');
    }
    /**
     * 删除目录/模块
     * @author MSQ 2021-8-10
     */
    public function deleteItem()
    {
        $database_id = $_POST['database_id'];
        $template_id = $_POST['template_id'];
        $item_id     = $_POST['item_id']; // 目录/模块ID 有则编辑，无则新增
        
        if (!$database_id || !$template_id || !$item_id) $this->error('DB02007:参数错误');

        $check = model('DbTemplateRelationItem')->checkDeleteItem($database_id,$template_id,$item_id);
        if ($check['code'] != 1) $this->error('DB02008:'.$check['msg']);

        Db::startTrans();
        $res = model('DbTemplateRelationItem')->deleteItem($template_id,$item_id);
        if (!$res) {
            Db::rollback();
            $this->error('DB02009:操作失败');
        }
        Db::commit();

        $this->success('操作成功');
    }
    /**
     * 获取模板二级模块
     * 用于新增总库自定义模板/编辑模块变量右侧列表可选模块
     * @author MSQ 2021-8-11
     */
    public function getTemplateSecondItem()
    {
        $template_id = $_POST['basicTemplateId'];
        $database_id = $_POST['database_id'];
        if (!$template_id) $this->error('DB02009:参数错误');

        $list = model('DbTemplateRelationItem')->getTemplateSecondItem($template_id);
        $this->success('获取成功',$list);
    }
    /**
     * 根据二级模块获取相关信息
     * 用于新增总库自定义模板/编辑模块变量右侧列表选择二级模块后渲染期目录及变量
     * @author MSQ 2021-8-11
     */
    public function getInfoBySecondItemId()
    {
        $template_id = $_POST['basicTemplateId'];
        $database_id = $_POST['database_id'];
        $item_id     = $_POST['item_id'];

        if (!$template_id || !$item_id) $this->error('DB02009:参数错误');

        $data = model('DbTemplateRelationItem')->getInfoBySecondItemId($template_id,$item_id);
        if ($data === false) $this->error('DB02010:未知错误');

        $this->success('获取成功',$data);
    }
    /**
     * 设置模板信息
     * 该方法包含新增/编辑/删除/排序-目录
     * @author MSQ 2021-8-11
     */
    public function setTemplateItemAdnQuestion()
    {
        #问题类型：1-单选题 2-多选题 3-下拉 4-附件上传 5-单行文本 6-多行文本 7-时间（Y-m-d）
        $template_id = $_POST['template_id'];
        $database_id = $_POST['database_id'];
        $data        = json_decode($_POST['data'],448);
        $delArr      = $_POST['del_arr'];
        $quote_template_id = $_POST['quote_template_id'];// 引用模板id

        $usercare_id = $this->auth->getUsercareinfo('id');
        if (!$database_id) $this->error('DB02011:参数错误');

        # 数据验证
        $checkRes = model('DbTemplate')->checkSetTemplate($database_id,$template_id,$data,$delArr,$quote_template_id);
        if ($checkRes['code'] != 1) $this->error('DB02012:'.$checkRes['msg']);
               
        Db::startTrans();
        $setRes = model('DbTemplate')->setTemplate($template_id,$database_id,$data,$usercare_id);
        if ($setRes['code'] !== 1) {
            Db::rollback();
            $this->error('DB02013:操作失败-'.$setRes['msg']);
        }
        $delRes = model('DbTemplate')->deleteItemAndQuestion($template_id,$delArr);
        if ($delRes !== true) {
            Db::rollback();
            $this->error('DB02014:删除失败');
        }
        Db::commit();
        $returnData['selectDirId'] = @$setRes['selectDirId'];
        $this->success('操作成功',$returnData);
    }
}
